const gulp = require('gulp'),
    path = require('path'),
    glob = require('glob'),
    fs = require('fs'),
    plugins = require('gulp-load-plugins'),
    $ = plugins({
        pattern: ['*']
    });

/**
 * 获取命令行参数，依赖 "minimist": "^1.2.0"
 */
const cmdOptions = (function () {
    
    let cmdArg1 = [{
        str: "env",
        init: "production",
    }, {
        str: "zip"
    }, {
        str: "wtask"
    }, {
        str: "tool"
    }];
    
    let getOptions = (cmdArg = cmdArg1) => {
        
        let options = {
            string: [],
            default: {}
        };
        cmdArg.forEach(function (v, i) {
            options.string.push(v.str);
            options.default[v.str] =  process.env.NODE_ENV || v.init ? v.init : null;
        });
        return options;
    };
    
    let options = $.minimist(process.argv.slice(2), getOptions());

    return options;
})();
    
const methods = (function () {
    let tools = {
        /**
         * getFileName 获取文件名
         * methods == all -- 带有文件后缀
         */
        getFileName: function (path, methods) {
            let filename;
            if (methods == 'all') {
                filename = path.substring(path.lastIndexOf("\\") + 1);
            } else {
                filename = path.substring(path.lastIndexOf("\\") + 1, path.lastIndexOf("."));
            }
            return filename;
        },
        whiteFile: function (path, data) {
            fs.writeFile(path, data,function(err){
                if(err) throw err;
                console.log("写入成功");
            });
        }
    };

    return tools;
})();

const tools = (function () {
    let tools = {
        
        // 存放 watch task
        watchTaskGroup: {},
        /**
         * 监听函数
         */
        watchTask: function (name, task) {
            if (!(name in this.watchGroup)) {
                this.watchGroup[name] = task;
            }
        },
        /**
         * saveversion
         * 用于保存当前版本
         */
        saveversion: function (name) {
            var timer = +new Date();
            name = name && name != 'null' ? name : timer;
            return gulp.src(['**/*.*', '!**/node_modules/**/*.*', '!release/**/*.*', '!version/**/*.*'])
                .pipe($.zip('version.' + name + '.zip'))
                .pipe(gulp.dest('version'));
        },
        /**
         * 删除文件
         * 依赖 "gulp-clean": "^0.3.2",
         */
        delete: function (path) {
            if (!path) return;
            gulp.src(path)
                .pipe($.clean())
        },
        
        /**
         * envDo
         * 传入两个函数，根据不同的参数返回制定环境下执行的函数
         */
        envDo: function (pro, dev) {
            if (cmdOptions.env === 'production') {
                return pro;
            } else if (cmdOptions.env === 'development') {
                return dev;
            }
        },

        /**
         * watchdo -- 监控文件变化
         * path -- {string} (监控文件)
         * ev -- {array} (监控类型)
         * fn -- {function} (执行函数)
         * option -- {object} (配置参数)
         *      -- unlink (boolean) (是否做删除关联)
         * 
         * 依赖： "gulp-watch": "^4.3.11",
         */
        watchdo: function (path, ev, fn, option) {
            let watcher = $.watch(path.watchpath),
                evlist = [];
            
            if (typeof ev == "function") {
                fn = ev;
                ev = 'change';
            }

            if (Array.isArray(ev)) {
                evlist = evlist.concat(ev);
            } else if (typeof ev == "string") {
                evlist.push(ev);
            }

            if (option.unlink) {
                watcher.on('unlink', function (path, details) {
                    if (typeof path.outpath != 'string') {
                        console.log('没有指定输出路径，无法对输出文件进行删除')
                    }
                    let filename = methods.getFileName(path, 'all'),
                        outpath = patch.outpath + filename;
                        
                    gulp.src(outpath).pipe($.clean());
                })
            }

            evlist.forEach(function (v, i) {
                watcher.on(evlist[i], fn);
            });
        }
    };
    return tools;
})();

const dodefault = (function () {
    let evdefault = {
        runwatch: function () {

            var watchGroup = tools.watchTaskGroup;
            for (let taskname in watchGroup) {
                if (watchGroup.hasOwnProperty(taskname)) {
                    let task = watchGroup[taskname];
                    task();
                }
            }
        }
    }
})();
// 文件管理，相关 task
{
    /**
     * 保存当前版本
     * 依赖 "gulp-zip": "^4.0.0",
     * 这里使用 options 配置 -- cmdOptions
     */
    gulp.task('saveversion', function () {
        tools.saveversion(cmdOptions.zip);
    });
}


gulp.task('default', function () {
    console.log('init');
    console.log(cmdOptions);
});

/**
 *  modul
 *  用于配合 gulp-load-plugins 输出 引入了那些插件模块，以及引入的名称
 *  形式如：{ moduleName: [] }
 *  使用模块的方式： $.moduleName
 */
gulp.task('module', function () {
    console.log($)
});

/**
 * 初始化项目时使用，完成后可以删除
 */

